package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbBankCardMapper;
import com.bwie.pojo.TbBankCard;
import com.bwie.pojo.TbKeepBaby;
import com.bwie.service.TbKeepBabyService;
import com.bwie.mapper.TbKeepBabyMapper;
import com.bwie.utils.R;
import com.bwie.vo.LoanVo;
import com.bwie.vo.PageInfoVo;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author lenovo
 * @description 针对表【tb_keep_baby】的数据库操作Service实现
 * @createDate 2025-07-03 09:55:42
 */
@Service
public class TbKeepBabyServiceImpl extends ServiceImpl<TbKeepBabyMapper, TbKeepBaby>
        implements TbKeepBabyService {


    @Autowired
    TbKeepBabyMapper tbKeepBabyMapper;

    @Autowired
    TbBankCardMapper tbBankCardMapper;

    @Override
    public R getKeepBabyList(PageInfoVo pageInfoVo) {

        Page<TbKeepBaby> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

        QueryWrapper<TbKeepBaby> wrapper = new QueryWrapper<>();

        wrapper.lambda().orderByDesc(TbKeepBaby::getPrice);
        Page<TbKeepBaby> tbKeepBabyPage = tbKeepBabyMapper.getKeepBabyList(page);

        return R.OK(tbKeepBabyPage);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R addToBank(LoanVo loanVo) {

        List<TbKeepBaby> tbKeepBabies = tbKeepBabyMapper.selectList(null);
        for (TbKeepBaby tbKeepBaby : tbKeepBabies) {

            tbKeepBaby.setPrice(tbKeepBaby.getPrice() - loanVo.getWithdrawPrice());

            if (loanVo.getWithdrawPrice() > tbKeepBaby.getPrice()) {
                return R.ERROR(500, "提现金额不得大于存钱宝金额");
            }

            tbKeepBabyMapper.updateById(tbKeepBaby);
        }

        List<TbBankCard> tbBankCards = tbBankCardMapper.selectList(null);

        for (TbBankCard tbBankCard : tbBankCards) {

            tbBankCard.setPrice2(tbBankCard.getPrice2() + loanVo.getRechargePrice());

            tbBankCardMapper.updateById(tbBankCard);
        }

        return R.OK();
    }


}




